package com.wnhz.work.yz.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Selection;
import android.text.Spannable;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.base.BaseRVAdapter;
import com.wnhz.work.yz.base.BaseViewHolder;
import com.wnhz.work.yz.bean.Finish1;
import com.wnhz.work.yz.bean.YuShouDetailsBean;
import com.wnhz.work.yz.bean.YuShouPayBean;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class YuShouDetailssActivity extends BaseActivity implements View.OnClickListener {
    private RecyclerView recyclerView;
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Finish1 event) {
        finish();
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);//反注册EventBus
        super.onDestroy();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yu_shou_details);
        EventBus.getDefault().register(this);
        //  MyApplication.getInstance().addDestoryActivity(this, "yushoudetails");
        initData();
        initTitle();
        initView();
        upLoad();
    }

    private String type, goods_id, name;

    private void initData() {
        type = getIntent().getStringExtra("type");
        goods_id = getIntent().getStringExtra("goods_id");
        name = getIntent().getStringExtra("name");
    }

    private void initView() {
        recyclerView = (RecyclerView) findViewById(R.id.recycler);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        //  recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.HORIZONTAL));
    }

    private void initTitle() {
        TextView title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("" + name);
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        TextView submit = (TextView) findViewById(R.id.submit);
        submit.setOnClickListener(this);
        submit.setText("下一步");
        findViewById(R.id.submit).setVisibility(View.VISIBLE);

    }

    @Override
    protected void onResume() {

        super.onResume();
    }

    private YuShouDetailsBean bean = new YuShouDetailsBean();

    private void upLoad() {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("type", type);
        map.put("goods_id", goods_id);
        showDialog();
        Set keys = map.keySet();
        if (keys != null) {
            Iterator iterator = keys.iterator();
            while (iterator.hasNext()) {
                Object key = iterator.next();
                Object value = map.get(key);
                Log.e("----" + key, ":" + value + "\n");
            }
        }
        XUtil.Post(Url.BOOKING_BOOKINGSKULIST, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    if ("1".equals(res)) {
                        Gson gson = new Gson();
                        bean = gson.fromJson(result, YuShouDetailsBean.class);
                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        str = info;
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                setData();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
            }
        });

    }

    private void setData() {

        recyclerView.setAdapter(new BaseRVAdapter(this, bean.getInfo()) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_yushou_details;
            }

            @Override
            public void onBind(final BaseViewHolder viewHolder, final int position) {
                viewHolder.getView(R.id.shop_img).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        startActivity(new Intent(YuShouDetailssActivity.this, ProjectListActivity.class)
                                .putExtra("goods_id", bean.getInfo().get(position).getGoods_id())
                                .putExtra("sku_id", bean.getInfo().get(position).getGoods_sku_id())
                                .putExtra("isYuShou", 123)
                                .putExtra("goods_name", bean.getInfo().get(position).getGoods_name()));
                    }
                });
                x.image().bind(viewHolder.getImageView(R.id.shop_img), bean.getInfo().get(position).getGoods_img());
                viewHolder.getTextView(R.id.shopping_number).setText("" + bean.getInfo().get(position).getGoods_num());
                viewHolder.getTextView(R.id.title).setText("" + bean.getInfo().get(position).getGoods_name());
                viewHolder.getTextView(R.id.sku).setText("" + bean.getInfo().get(position).getCate_name());
                viewHolder.getTextView(R.id.desc).setText("" + bean.getInfo().get(position).getGoods_sku_info());
                viewHolder.getTextView(R.id.room_num).setText("库存" + bean.getInfo().get(position).getGoods_else_nums());
                viewHolder.getTextView(R.id.price).setText("" + bean.getInfo().get(position).getGoods_price());
                viewHolder.getTextView(R.id.old_price).setText("" + bean.getInfo().get(position).getGoods_oprice());
                //
                viewHolder.getImageView(R.id.ll_add).setTag(viewHolder.getTextView(R.id.shopping_number));
                viewHolder.getImageView(R.id.ll_add).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TextView textView = (TextView) v.getTag();
                        int nums = 1;
                        try {
                            nums = Integer.parseInt(textView.getText().toString()) + 1;
                        } catch (Exception w) {
                            nums = 1;
                        }
                        if (nums > Integer.parseInt(bean.getInfo().get(position).getGoods_else_nums())) {
                            MyToast("库存不足");
                            nums = Integer.parseInt(bean.getInfo().get(position).getGoods_else_nums());
                        }
                        bean.getInfo().get(position).setGoods_num(nums + "");
                        //
                        textView.setText("" + nums);
                    }
                });
                viewHolder.getImageView(R.id.reduce).setTag(viewHolder.getTextView(R.id.shopping_number));
                viewHolder.getImageView(R.id.reduce).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TextView textView = (TextView) v.getTag();
                        int nums = 1;
                        try {
                            nums = Integer.parseInt(textView.getText().toString()) - 1;
                        } catch (Exception w) {
                            nums = 1;
                        }
                        if (nums == -1) {
                            MyToast("不能再小了");
                            nums = 0;
                        }
                        bean.getInfo().get(position).setGoods_num(nums + "");

                        //
                        textView.setText("" + nums);
                    }
                });
                viewHolder.getTextView(R.id.shopping_number).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(final View v) {
                        final AlertDialog.Builder builder = new AlertDialog.Builder(YuShouDetailssActivity.this);
                        View view = View.inflate(YuShouDetailssActivity.this, R.layout.dialog_edit, null);
                        TextView queding1 = (TextView) view.findViewById(R.id.queding1);
                        final TextView quxaio1 = (TextView) view.findViewById(R.id.quxiao1);
                        final EditText shopping_number = (EditText) view.findViewById(R.id.shopping_number);
                        shopping_number.setText(bean.getInfo().get(position).getGoods_num() + "");

                        shopping_number.postInvalidate();
                        //切换后将EditText光标置于末尾
                        CharSequence charSequence = shopping_number.getText();
                        if (charSequence instanceof Spannable) {
                            Spannable spanText = (Spannable) charSequence;
                            Selection.setSelection(spanText, charSequence.length());
                        }

                        builder.setView(view);
                        final AlertDialog show = builder.show();
                        Window dialogWindow = show.getWindow();
                        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
                        dialogWindow.setGravity(Gravity.CENTER);
                        dialogWindow.setAttributes(lp);
                        queding1.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                int nums = Integer.parseInt(bean.getInfo().get(position).getGoods_num());
                                try {
                                    nums = Integer.parseInt(shopping_number.getText().toString());
                                } catch (Exception e) {
                                    nums = Integer.parseInt(bean.getInfo().get(position).getGoods_num() + "");
                                }
                                if (nums > Integer.parseInt(bean.getInfo().get(position).getGoods_else_nums())) {
                                    MyToast("库存不足");
                                    nums = Integer.parseInt(bean.getInfo().get(position).getGoods_else_nums());
                                }
                                bean.getInfo().get(position).setGoods_num(nums + "");
                                viewHolder.getTextView(R.id.shopping_number).setText(nums + "");
                                show.dismiss();
                            }
                        });
                        quxaio1.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                show.dismiss();
                            }
                        });
                    }
                });
            }
        });
    }

    private String str = "没有商品";
    private boolean flag = false;
    private YuShouPayBean.InfoEntity infoBean = new YuShouPayBean.InfoEntity();

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;
            case R.id.submit:
                try {
                    ArrayList<YuShouDetailsBean.InfoEntity> packageX = new ArrayList<>();
                    flag = false;
                    for (int i = 0; i < bean.getInfo().size(); i++) {
                        if (Integer.parseInt(bean.getInfo().get(i).getGoods_num()) > 0) {
                            packageX.add(bean.getInfo().get(i));
                            flag = true;
                        }
                    }
                    if (!flag) {
                        MyToast("购买数量为0");
                        return;
                    }
                    //Log.e("left====", packageX.size() + "");
                    if (MyApplication.getInstance().getUserBean() == null) {
                        MyToast("请登录!");
                        Intent intent2 = new Intent(this, LoginNewActivity.class);
                        startActivity(intent2);
                        return;
                    }
                    ifCan(packageX, type);
                } catch (Exception e) {
                    MyToast("" + str);
                    return;
                }

                break;
        }
    }

    private void ifCan(final ArrayList<YuShouDetailsBean.InfoEntity> packageX, final String type) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", MyApplication.getInstance().getUserBean().getToken());
        map.put("type", type);

        StringBuffer sb = new StringBuffer("[");
        for (int i = 0; i < packageX.size(); i++) {
            sb.append(" {\n" +
                    "     \"goods_id\":\"" + packageX.get(i).getGoods_id() + "\",\n" +
                    "     \"sku_id\":\"" + packageX.get(i).getGoods_sku_id() + "\",\n" +
                    "     \"nums\":\"" + packageX.get(i).getGoods_num() + "\"\n" +
                    "     }");
            if (i != packageX.size() - 1) {
                sb.append(",");
            }
        }
        sb.append("]");
        map.put("json_str", sb.toString());
        showDialog();

        XUtil.Post(Url.BOOKING_BOOKINGMAKEORDER, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    if ("1".equals(res)) {
                        Gson gson = new Gson();
                        YuShouPayBean ysb = gson.fromJson(result, YuShouPayBean.class);
                        infoBean = ysb.getInfo();
                        startActivity(new Intent(YuShouDetailssActivity.this, YuShouPayActivity.class)
                                .putExtra("bean", packageX)
                                .putExtra("type", type)
                                .putExtra("infoBean", infoBean));
                    } else {
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        upLoad();
                        MyToast(info);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                findViewById(R.id.submit).setVisibility(View.VISIBLE);
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
            }
        });

    }


}
